<template>
  <!-- 在线对话子组件 -->
  <div id="box">
    <div id="onlineChat">
      <div v-show="logoutBtn" class="topIcon" @click="logout">
        <img src="../../assets/images/home/tuichu.png" />
      </div>
      <iframe
        ref="myiframe"
        name="myiframe"
        class="iframe"
        id="myiframe"
        style="width: 0; height: 0"
        :src="`/speechService/examples/index.html`"
        frameborder="0"
        scrolling="no"
      ></iframe>
      <!-- 聊天框 -->
      <div class="chat_commento">
        <div class="chat_top">
          {{ Myname }}
          <slot name="reduceandenlarge"></slot>
        </div>
        <!-- <div class="line"></div> -->
        <!-- middle -->
        <div class="chat_middle" id="chat_middle_item">
          <!-- 左边 -->
          <!-- roletype !== 1 表示为亲属或养老院第三方（左侧） roletype == 1 表示老人角色（右侧） -->
          <div
            v-show="item.message !== ' '"
            v-for="(item, index) in chatArray"
            :key="index"
            :class="{
              chat_left: item.roletype !== 1,
              chat_right: item.roletype == 1,
              clearfix: true,
            }"
          >
            <!-- 头像和名称 -->
            <div
              :class="{
                chat_left_item_1: item.roletype !== 1,
                chat_right_item_1: item.roletype == 1,
              }"
            >
              <!-- //  0: 子女或亲属 1: 老人本身 2: 机构  -->
              <img
                id="userimg"
                :src="
                  item.roletype == 2
                    ? require('../../assets/images/users/xiaofu.jpg')
                    : item.roletype == 1
                    ? require('../../assets/images/users/oldmale.png')
                    : item.roletype == 1
                    ? require('../../assets/images/users/oldfemale.png')
                    : require('../../assets/images/users/child.png')
                "
                alt=""
              />
              <span v-if="item.roletype !== 1">{{ item.name }}</span>
              <span v-else>我</span>
            </div>
            <div
              :class="{
                chat_left_item_2: item.roletype !== 1,
                chat_right_item_2: item.roletype == 1,
              }"
            >
              <!-- 聊天时间 -->
              <div
                :class="{
                  chat_time: item.roletype !== 1,
                  chat_right_time: item.roletype == 1,
                }"
              >
                {{ item.time }}
              </div>
              <div>
                <!-- 聊天内容 -->
                <div
                  :class="{
                    chat_left_content: item.roletype !== 1,
                    chat_right_content: item.roletype == 1,
                  }"
                  v-show="item.modeltype==1"
                >
                  {{ item.message }}
                  <img
                    class="warn"
                    @click="showWarnwhy($event,item)"
                    v-show="item.flag == 'fail'"
                    src="../../assets/images/global/warn.png"
                  />
                </div>
                <!-- 聊天语音 -->
                <div
                  :class="{
                    chat_left_content: item.roletype !== 1,
                    chat_right_content: item.roletype == 1,
                  }"
                  v-show="item.modeltype==2"
                  :style="item.modeltype == 2 ? 'cursor: pointer;' : 'cursor: default;'"
                  @click="controlAudio(item)"
                >
                  <!-- 点击播放语音 -->
                  <img
                      class="audio" 
                      v-show="item.status == 'stop'"
                      src="../../assets/images/global/pause.png"
                      style="vertical-align:middle;"
                  />
                  <!-- 点击停止语音播放 -->
                  <img
                      class="audio"
                      v-show="item.status == 'play'"
                      src="../../assets/images/global/play.gif"
                      style="vertical-align:middle;"
                  />
                  <!-- 语音时长 -->
                  <span style="display:inline-block;margin-left:10px;font-size:1rem;">{{ item.duration }}"</span>
                  <div :style="'width:'+autoAudioLength(item.duration)+';display:inline-block;'"></div>
                </div>
                <!-- <img class="warn" @click="showWarnwhy($event)" v-show="item.flag=='fail'" src="../../assets/images/global/warn.png" /> -->
              </div>
            </div>
          </div>
        </div>
        <!-- line -->
        <div class="line"></div>
        <!-- foot -->
        <div class="chat_foot">
          <!-- context  -->
          <textarea
            v-focus="true"
            class="chat_context"
            @keydown="handleKeyCode"
            v-model="chat_context_item"
            id="chat_context_item"
            cols="30"
            rows="10"
          ></textarea>
          <div
            v-show="btnDebug"
            class="chat_log"
            id="button"
            @click="logmode()"
          >
            调试
          </div>
          <div class="chat_commit" id="commit_button" @click="commit()">发送</div>
        </div>
      </div>
      <!-- 日志列表 -->
      <div class="logList" v-show="showlog && btnDebug" id="logList">
        <div class="chat_top" style="position: sticky; top: 0">日志列表</div>
        <!-- <div class="line"></div> -->
        <div class="logContent" id="logContent">
          <ul>
            <li v-for="(item, index) in chatLog" :key="index + '_' + index">
              <span class="logTime">{{ item.time }}</span
              ><br />
              <span class="logMessage">{{ item.content }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="awakenIcon" @click="awaken">
        <img src="../../assets/images/home/awaken.png" />
    </div>
  </div>
</template>
<script>
import { mapMutations, mapState } from "vuex";
import mqtt from "mqtt";
// import moment from 'moment';
// import { trtcSpeech, chatMessage, chatRecoeds } from "../../api/index";
import { chatMessage, chatRecoeds,cancel,cancel0,createTaskid,getAudioUrl } from "../../api/index";
import mp3 from "../../assets/music/start.mp3";
import mp30 from "../../assets/music/end.wav";
import Cookies from 'js-cookie'
// import axios from 'axios' // 安装axios后引入
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
} from "../../utils/sysconstant";
// mqtt协议规则
const roomoptions = {
  connectTimeout: 40000,
  clientId: "appmqttjs_" + Math.random().toString(16).substr(2, 8),
  username: MQTT_USERNAME,
  password: MQTT_PASSWORD,
  clean: true,
};
export default {
  name: "onlineChat",
  data() {
    return {
      Myname: "",
      chat_context_item: "",
      roomClient: null, //ws
      Connected: false,
      chattopic: "",
      hastatustopic: "",
      // 当前账号：1   0: 子女或亲属 1: 老人本身 2: 机构
      // chatArray:[],
      showlog: true,
      btnDebug: false,
      appAnswerMusic: null,
      appAnswerEndMusic: null,
      volume:50,
      remark:'',
      mes:'',
      // js语音合成
      speechUtterance:null,
      // 百度语音合成
      messageVoice:null,
      // 语音消息
      currentAudio:null,
      endTime:null,
      interval:null
      // token:''
    };
  },
  props: {
    logoutBtn: {
      type: Boolean,
      required: false,
      default: true,
    },
    showchat: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  directives: {
    focus: {
      inserted: function (el, { value }) {
        if (value) {
          el.focus();
        }
      },
    },
  },
  computed: {
    ...mapState({
      currentUserId: (state) => state.currentUserId, //当前的用户id
      loginUserInfo: (state) => state.loginUserInfo,
      userInfoDetails: (state) => state.userInfoDetails, //用户详细信息
      chatClient: (state) => state.chatClient, //聊天的mq
      chatLog: (state) => state.chatLog, //聊天日志
      chatArray: (state) => state.chatArray, //聊天内容
      token: (state) => state.token,
    }),
  },
  watch: {
    chat_context_item(val) {
      this.chat_context_item = val;
    },
    // 监听聊天内容改变时，页面滚动至聊天记录最底部
    chatArray(val) {
      console.log('val-------',val)
      // 没有聊天记录
      if(val.length ==0)return false;
      // 当前收到信息为本人发送
      if(val[val.length-1].roletype==1) return false;
      // 默认所有语音消息暂停播放
      val.forEach(item=>{
        if(item.modeltype == 2){
          item.status='stop'
        }
      })

      if(val[val.length-1].roletype!==1){
        if (this.endTime){
          clearTimeout(this.endTime);
          if (document.getElementById("myiframe"))
            document
              .getElementById("myiframe")
              .contentWindow.postMessage({ cmd: "chatend" }, "*");
       } 
      }

      // 播放最新语音消息
      if(val[val.length-1].modeltype==2 && val[val.length-1].time == new Date().Format("yyyy-MM-dd hh:mm:ss").toString()){
        // 最新一条消息不是本人发送且当前有语音消息正在播放，取消当前播放
        if(this.currentAudio !== null){
          this.currentAudio.pause()
          this.currentAudio.removeAttribute('src')
          this.currentAudio.load()
          this.currentAudio= null
        }
        this.playAudio(val[val.length-1],true)
      }

      let ele = document.getElementById("chat_middle_item");
      if (ele.scrollHeight > ele.clientHeight) {
        ele.scrollTop = ele.scrollHeight;
        ele.scrollTo({ top: ele.scrollHeight, behavior: "smooth" });
      }
      this.updated()
    },
    
    // 监听日志列表
    chatLog() {
      this.$nextTick(function () {
        let elelogContent = document.getElementById("logList");
        if (elelogContent.scrollHeight > elelogContent.clientHeight) {
          elelogContent.scrollTop = elelogContent.scrollHeight;
          elelogContent.scrollTo({
            top: elelogContent.scrollHeight,
            behavior: "smooth",
          });
        }
      });
    },
  },
  created() {
    this.Myname = this.userInfoDetails.account.name;
    this.chattopic = this.currentUserId + "/chat";
    this.hastatustopic = this.currentUserId + "/chat/mpd/state";
    this.getChatRecords();
      this.appAnswerMusic = null;
      this.appAnswerMusic = new Audio();
      this.appAnswerMusic.src = mp3;
      this.appAnswerEndMusic=null
      this.appAnswerEndMusic = new Audio();
      this.appAnswerEndMusic.src = mp30;

    if(localStorage.getItem("ttsSelectedValue") == "jstts"){
      this.initSpeack()
    }
  },
  mounted() {
    // this.speak();
    // let durationTime = localStorage.getItem("durationSelected");
    // console.log(durationTime * 1000,'durationTime');
    // 是否显示调试模式
    // if (localStorage.getItem("modeSelected") == "1") this.btnDebug = true;
    if (Cookies.get("modeSelected") == "1") this.btnDebug = true;
    this.connectMq();
    console.log("语音聊天mounted");
    // 没有配置过麦克风
    // if (!localStorage.getItem("audioSelectedValue")) {
    if (!Cookies.get("audioSelectedValue")) {
      console.log("没有配置过麦克风");
      // navigator.mediaDevices?.enumerateDevices 获取当前设备上可用的媒体设备（如摄像头、麦克风等）的列表
      if (!navigator.mediaDevices?.enumerateDevices) {
        console.log("enumerateDevices() not supported.");
      } else {
        // navigator.mediaDevices.enumerateDevices 设备列表是一个 Promise 对象，它将返回一个包含设备信息的数组。
        navigator.mediaDevices
          .enumerateDevices()
          .then((devices) => {
            for (var i = 0; i < devices.length; i++) {
              // kind为audioinput 设置列表中的音频输入设备
              // label 表示设备的可读标签，通常包含设备的名称或描述。
              if (devices[i].kind == "audioinput") {
                // localStorage.setItem("audioSelectedValue", devices[i].label);
                Cookies.set("audioSelectedValue", devices[i].label);
                break;
              }
            }
          })
          .catch((err) => {
            console.error(`${err.name}: ${err.message}`);
          });
      }
    }
    this.updated();
    this.$nextTick(function () {
      let elelogContent = document.getElementById("logList");
      if (elelogContent.scrollHeight > elelogContent.clientHeight) {
        elelogContent.scrollTop = elelogContent.scrollHeight;
        elelogContent.scrollTo({
          top: elelogContent.scrollHeight,
          behavior: "smooth",
        });
      }
    });
    window.addEventListener("onbeforeunload", () => {
      console.log("页面关闭onbeforeunload");
    });
    window.addEventListener("onload", () => {
      console.log("页面关闭onload");
    });

    var content='百度tts'
    if(localStorage.getItem("ttsSelectedValue") == "jstts"){
      content='jstts'
    }
    this.$store.commit("setChatLog", {
      time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      content: "文字转语音方式:"+ content,
    });
  },
  methods: {
    ...mapMutations(["setChatClient", "setChatLog", "setChatArray","deleteErrorChat"]),
    // 去除红色感叹号
    showWarnwhy(e,item) {
      console.log('item',item,e)
      // e.target.style = "display:none";
      this.$store.commit("deleteErrorChat", item.id);
      this.commitrepeat(item.message)
    },
    // 重新发送失败的消息
    async commitrepeat(message) {
      var param = {
        model_type: 1,
        role_type: 1,
        user_id: this.currentUserId,
        sender_type: 2,
        sender_id: this.loginUserInfo.userId,
        sender_name: this.userInfoDetails.account.name,
        chat_message: message,
        volume:this.volume,
        remark:this.remark
      };
      console.log('发送消息',param)
      await chatMessage(param)
        .then((res) => {
          console.log("调用接口的结果", res);
          if (res.code == 0 && this.chat_context_item.trim !== "") {
            console.log("发送成功", res);
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: message,
              flag: "success",
              modeltype:1,
              id:Date.parse(new Date())
            });
          } else {
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: message,
              flag: "fail",
              modeltype:1,
              id:Date.parse(new Date())
            });
            this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "消息发送失败："+ res.code+"-"+res.message +"    当前token:"+window.localStorage["token"] +",当前token过期时间："+window.localStorage["expiration"],
            });
          }
          this.chat_context_item = "";
          document.getElementById("chat_context_item").value = "";
          this.updated();
        })
        .catch((error) => {
          console.log("获取失败", error);
          this.$store.commit("setChatArray", {
            roletype: 1,
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            name: "我",
            message: message,
            flag: "fail",
            modeltype:1,
            id:Date.parse(new Date())
          });

          this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "消息发送失败"+ error +"    当前token:"+window.localStorage["token"] +",当前token过期时间："+window.localStorage["expiration"],
          });
          this.updated();
        });
    },
    // 创建mq连接
    connectMq() {
      let that = this;
      var _this = this;

      //未创建mq
      if (!this.chatClient) {
        console.log("**************在线聊天开始连接**************");
        that.$store.commit("setChatLog", {
          time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
          content: "在线聊天开始连接mq",
        });
        that.roomClient = mqtt.connect(MQTT_SERVICE, roomoptions);
        console.log(that.roomClient,'----------')
        that.$store.commit("setChatClient", that.roomClient);
        console.log("mqtt是否链接成功", that.roomClient.connected);
        if (!that.roomClient.connected) {
          // mqtt连接
          that.roomClient.on("connect", () => {
            console.log("**************在线聊天mq连接成功**************");
            that.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "在线聊天mq连接成功",
            });
            that.Connected = true; //ws连接成功
            //连接成功后订阅消息
            //qos为0 最多一次的传输
            that.roomClient.subscribe(that.chattopic, { qos: 0 }, (error) => {
              if (!error) {
                that.$store.commit("setChatLog", {
                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                  content: "在线聊天mq订阅成功",
                });
                console.log("**************在线聊天mq订阅成功**************",that.chattopic);
              } else {
                that.$store.commit("setChatLog", {
                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                  content: "在线聊天mq订阅失败",
                });
                console.log("**************在线聊天mq订阅失败**************",that.chattopic);
              }
            });
            that.roomClient.subscribe(
              that.hastatustopic,
              { qos: 0 },
              (error) => {
                if (!error) {
                  that.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "在线聊天HAmq订阅成功",
                  });
                  console.log(
                    "**************HAmq订阅成功**************",
                    that.hastatustopic
                  );
                } else {
                  that.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "在线聊天HAmq订阅失败",
                  });
                  console.log(
                    "**************HAmq订阅失败**************",
                    that.hastatustopic
                  );
                }
              }
            );
          });
        }
        // 断开发起重连
        that.roomClient.on("reconnect", (error) => {
          that.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "在线聊天mq正在重连",
          });
          console.log("在线聊天mq正在重连:", error);
        });
        that.roomClient.on("message", (topic, message) => {
          let data = JSON.parse(message);
          _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "收到来自"+ topic +"的消息:"+data.message,
          });
          console.log("收到来自", topic, "的消息", data);
          if(data!== 1){
            this.volume=data.soundVolume!== undefined ? parseInt(data.soundVolume) : 50;
          }
          if (topic == that.chattopic) {
            if (parseInt(data.roletype) !== 1 && data.message) {
              this.mes =data.message
              console.log('接收到消pushData消息，即将进行播放',this.mes,'data.message')
              
              this.pushData(data);
              document.onkeydown = function(e) {
                var ev = (typeof event!= 'undefined') ? window.event : e;
                if(ev.keyCode == 13) {
                  return false;
                }
              }
              // document.getElementById('commit_button').setAttribute('style', 'background-color: #64a2d4; pointer-events:none;');
              console.log(document.getElementById('commit_button'))
              // 取消正在播放的js合成语音
              if(localStorage.getItem("ttsSelectedValue") == "jstts"  && window.speechSynthesis.speaking){
                console.log('js语音播放取消')
                window.speechSynthesis.cancel()
                _this.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "--取消正在播放的js语音--",
                });
              }
              if(data.modeltype==1){
                  // 销毁上一个未播放完成的百度 文字转语音
                  if(localStorage.getItem("ttsSelectedValue") !== "jstts" && _this.messageVoice !== null){
                    _this.$store.commit("setChatLog", {
                      time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                      content: "销毁上一个百度语音"+_this.messageVoice.getAttribute('src'),
                    });
                    console.log('---------销毁上一个百度语音',_this.messageVoice.getAttribute('src'))
                    clearInterval(this.interval)
                    cancel0();
                    cancel();
                    _this.messageVoice.pause()
                    _this.messageVoice.removeAttribute('src')
                    _this.messageVoice.load()
                    _this.messageVoice= null
                  }
                  // 销毁上一个正在播放的语音
                  if(_this.currentAudio !== null){
                    _this.currentAudio.pause()
                    _this.currentAudio.removeAttribute('src')
                    _this.currentAudio.load()
                    _this.currentAudio= null
                  }

                  // 收到的消息类型为文字
                  // 判断当前使用哪种方式进行语音合成
                  if(localStorage.getItem("ttsSelectedValue") == "jstts"){
                    this.speak0({text:this.mes,volume:this.volume/100});
                  }else{
                    this.speak(this.mes);
                  }
              }

              // 播放接收到的消息message
              // {
              //   "id":0,
              //   "modeltype":1, // 文字
              //   "userID":"16427281230",
              //   "roletype":2,
              //   "senderType":3,
              //   "senderID":"guest_xckw_service1",
              //   "senderName":"科委客服中心",
              //   "message":"你好", //消息内容
              //   "requestTime":"2023-10-20T11:20:00.52125408:00"
              // }
            }
          }
          // if (topic == that.hastatustopic) {
          //   // if (parseInt(data) == 1) {
          //     console.log("收到ha消息",that.hastatustopic,'that.hastatustopic',data);
          //     if (document.getElementById("myiframe")) {
          //       that.opentimeIdenty('HA');
          //     }
          //   // }
          // }
        });
        //如果连接错误，打印错误
        that.roomClient.on("error", function (err) {
          that.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "在线聊天mq连接错误",
          });
          console.log("在线聊天mq连接错误了 err=>", err);
          // that.Connected = false;
          if (that.Connected) {
            that.roomClient.end();
          }
          that.Connected = false;
        });
      }
    },
    // 语音合成
    async speak(text) {
      // var _this=this
      this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        content: "调用百度语音合成接口",
      });
      var volume= Math.floor(this.volume/10)
      this.messageVoice=null
      this.messageVoice=new Audio()
      console.log('调用百度语音合成接口')

      var param={
        "token":this.token,
        "text": text,
        "format": "mp3-16k", //音频格式
        // "format": "wav", //音频格式
        // "voice": 0, //音库，度小美
        "voice": 111, //音库，度小萌
        "lang": "zh",
        "speed": 5, //中语速
        "pitch": 5, // 中音调
        "volume": volume, //音量
        "enable_subtitle": 0 //0表示不开启字幕时间戳
      }
      // 创建语音合成任务
      await createTaskid(param)
        .then(async (res) => {
          if (res.status == 200) {
            var param0={
              'token':this.token,
              'task_ids':[res.data.task_id]
            }
            // 查询语音合成url
            await getAudioUrl(param0)
            .then((response) => {
              if (response.status == 200) {
                console.log(response)
                
                if(response.data.tasks_info[0].task_status=='Success'){
                  console.log('获取语音url成功',response.data.tasks_info[0].task_result.speech_url)
                  this.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "获取语音url成功"+response.data.tasks_info[0].task_result.speech_url,
                  });
                  var src=response.data.tasks_info[0].task_result.speech_url
                  // 需要将百度语音合成返回的url由http开头替换为https开头
                  this.messageVoice.src=src.replace("http","https")
                  // this.messageVoice.src=response.data.tasks_info[0].task_result.speech_url
                  this.messageVoice.play()
                  this.messageVoice.addEventListener('ended', function () {
                      document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
                      console.log('播音结束');
                      this.$store.commit("setChatLog", {
                        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                        content: "trtc---开始语音识别  ",
                      });
                      if (document.getElementById("myiframe")) {
                        this.opentimeIdenty('mq');
                      }
                  }, false);
                }
                if(response.data.tasks_info[0].task_status=='Running'){
                  console.log('音频合成中')
                  this.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "音频合成中",
                  });
                  this.interval= setInterval(async ()=>{
                    console.log('再次调用-------')
                      // 查询语音合成url
                      await getAudioUrl(param0)
                      .then((response) => {
                        if (response.status == 200) {
                          if(response.data.tasks_info[0].task_status=='Success'){
                            clearInterval(this.interval)
                            console.log('获取语音url成功',response.data.tasks_info[0].task_result.speech_url)
                            this.$store.commit("setChatLog", {
                              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                              content: "获取语音成功"+response.data.tasks_info[0].task_result.speech_url,
                            });
                            this.messageVoice.pause()
                            this.messageVoice.removeAttribute('src')
                            this.messageVoice.load()
                            this.messageVoice= null
                            this.messageVoice=new Audio()
                            var src=response.data.tasks_info[0].task_result.speech_url
                            console.log('src',src)
                            this.messageVoice.src=src.replace("http","https")
                            console.log('this.messageVoice.src',this.messageVoice.src)
                            this.messageVoice.play()
                            var _this=this

                            //开始播放
                            this.messageVoice.addEventListener('play', function () {
                              _this.$store.commit("setChatLog", {
                                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                content: "语音开始播放---",
                              });
                            }, false);

                            //播放中
                            this.messageVoice.addEventListener('playing', function (e) { 
                              console.log("播放中",e);
                              document.getElementById('commit_button').setAttribute('style', 'background-color: #64a2d4; pointer-events:none;');
                              _this.$store.commit("setChatLog", {
                                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                content: "语音播放中---",
                              });
                            });

                            var iswaiting = false
                            var count=0
                            //加载中
                            this.messageVoice.addEventListener('waiting', function () { 
                                console.log("加载中");
                                iswaiting=true
                                _this.$store.commit("setChatLog", {
                                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                  content: "语音加载中---"+iswaiting +'---token:'+window.localStorage["expiration"],
                                });
                                count++
                                var timer=setTimeout(() => {
                                  if(iswaiting ){
                                    _this.messageVoice.pause()
                                    _this.messageVoice.play()
                                    _this.$store.commit("setChatLog", {
                                      time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                      content: "语音加载超时，重新播放",
                                    });
                                  }
                                }, 10 * 1000);
                                if(count>3){
                                  clearTimeout(timer)
                                  count=0
                                  _this.messageVoice.pause()
                                  iswaiting=false
                                }
                            });

                            // 监听 canplay 事件
                            this.messageVoice.addEventListener('canplay', function() {
                              count=0
                              iswaiting=false  
                              _this.$store.commit("setChatLog", {
                                      time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                      content: "音频可以播放,无需缓冲。",
                                    });
                              console.log("音频现在可以播放了，不会再因需要缓冲更多数据而停止。");
                            });

                            // 监听 canplaythrough 事件
                            this.messageVoice.addEventListener('canplaythrough', function() {
                              count=0
                              iswaiting=false  
                              _this.$store.commit("setChatLog", {
                                      time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                      content: "音频可以从头播放到尾",
                                    });
                              console.log("音频可以从头播放到尾，无需再次停止缓冲。");
                            });

                            //网速失速
                            this.messageVoice.addEventListener('stalled', function(e) {
                              console.log('stalled')
                              console.log(e)
                              _this.$store.commit("setChatLog", {
                                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                  content: "语音数据不可用---"+ JSON.stringify(e),
                              });
                            })

                            // 播放错误
                            this.messageVoice.addEventListener('error', function () {
                              count=0
                              document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
                              _this.$store.commit("setChatLog", {
                                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                content: "语音播放错误---"+JSON.stringify(_this.messageVoice.error)+"  code----"+_this.messageVoice.error.code,
                              });
                            }, false);

                            // 播放结束
                            this.messageVoice.addEventListener('ended', function () {
                              count=0
                              document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
                                console.log('播音结束');
                                _this.$store.commit("setChatLog", {
                                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                  content: "播放结束",
                                });
                                _this.$store.commit("setChatLog", {
                                  time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                                  content: "trtc---开始语音识别",
                                });
                                if (document.getElementById("myiframe")) {
                                  _this.opentimeIdenty('mq');
                                }
                            }, false);
                          }
                          if(response.data.tasks_info[0].task_status=='Running'){
                            console.log('音频合成中')
                            this.$store.commit("setChatLog", {
                              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                              content: "音频合成中",
                            });
                          }
                          if(response.data.tasks_info[0].task_status=='Failure'){
                            console.log('音频合成失败')
                            this.$store.commit("setChatLog", {
                              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                              content: "音频合成失败",
                            });
                            clearInterval(this.interval)
                          }
                        } else {
                          document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
                          console.log("调用接口失败");
                        }
                      })
                      .catch((error) => {
                        document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
                        console.log("获取失败", error);
                      });
                  },1000)
                }
                if(response.data.tasks_info[0].task_status=='Failure'){
                  console.log('音频合成失败')
                  this.$store.commit("setChatLog", {
                    time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                    content: "音频合成失败",
                  });
                  clearInterval(this.interval)
                }
              } else {
                console.log("调用接口失败");
              }
            })
            .catch((error) => {
              console.log("获取失败", error);
              document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
              this.$store.commit("setChatLog", {
                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                content: "调用查询语音url接口失败",
              });
            });
          } else {
            document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
            console.log("调用接口失败");
          }
        })
        .catch((error) => {
          document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
          console.log("获取失败", error);
          this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "调用创建任务接口失败",
          });
        });
    },
    pushData(data) {
      if(data.modeltype == 1){
        // 文字
        this.$store.commit("setChatArray", {
          roletype: data.roletype,
          time: new Date().Format("yyyy-MM-dd hh:mm:ss"), //moment(data.requestTime).format('YYYY-MM-DD HH:mm:ss'),
          name: data.senderName,
          message: data.message,
          modeltype:data.modeltype,
          id:Date.parse(new Date())
        });
      }else{
        // 语音
        var audio=new Audio()
        audio.src=data.message
        var duration=audio.duration
        if (isNaN(duration)) {
          audio.currentTime = 1e101;
          audio.ontimeupdate = () => {
            audio.ontimeupdate = () => { return; };
            // 不重新设置currtTime,会直接触发audio的ended事件，因为之前将currentTime设置成了一个比音频时长还大的值。所以要将currentTime重置为初始状态。
            // 注: 这里有一个问题，直接设置为0 是不起作用的。需要重新设置一下audio.currentTime = 1e101;然后再设置为
            audio.currentTime = 1e101;
            audio.currentTime = 0;
            duration=Math.ceil(audio.duration)

            var data0={
              roletype: data.roletype,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"), //moment(data.requestTime).format('YYYY-MM-DD HH:mm:ss'),
              name: data.senderName,
              message: data.message,
              status:'stop',
              modeltype:data.modeltype,
              duration: duration,
              id:Date.parse(new Date())
            }
            this.$store.commit("setChatArray",data0 );
          }
        }
      }
      this.updated();
    },
    logout() {
      //退出到首页
      this.$router.push("/");
      // this.roomClient.end();
    },
    beforeDestroy() {
      // 取消正在进行的语音合成

      // 取消重复调用的定时器

      // 取消正在进行的语音识别

      // 暂停并销毁正在播放的js文字转语音mp3文件
      if(localStorage.getItem("ttsSelectedValue") == "jstts"  && window.speechSynthesis.speaking){
        window.speechSynthesis.cancel()
      }else{
      // 暂停并销毁正在播放的百度文字转语音mp3文件
        clearInterval(this.interval)
        cancel0();
        cancel();
        this.messageVoice.pause()
        this.messageVoice.removeAttribute('src')
        this.messageVoice.load()
        this.messageVoice= null
        // 销毁正在播放的语音
        if(this.currentAudio !== null){
          this.currentAudio.pause()
          this.currentAudio.removeAttribute('src')
          this.currentAudio.load()
          this.currentAudio= null
        }
      }
      // 取消正在播放的消息语音mp3文件
      if(this.currentAudio !== null){
        this.currentAudio.pause()
        this.currentAudio.removeAttribute('src')
        this.currentAudio.load()
        this.currentAudio= null
      }
      // 销毁使用的对象

      // 断开聊天使用的mq
      this.chatClient=null
      this.roomClient.end(true)
      this.roomClient=null
      console.log('this.chatClient',this.chatClient)
      this.chatClient.end();
      console.log('this.chatClient',this.chatClient)
      this.$store.commit("setChatClient", null);
      console.log('this.chatClient',this.chatClient)
      console.log("页面关闭销毁");
    },
    destroyed() {
      console.log("页面关闭销毁---");
      // if(this.roomClient)
    },
    // 聊天信息定位到最下方
    updated: function () {
      console.log('定位------------------')
      this.$nextTick(function () {
        var div = document.getElementById("chat_middle_item");
        if (div) div.scrollTop = div.scrollHeight;
      });
    },
    // 对方的话念完开始语音识别
    opentimeIdenty(type) {
      // let durationTime = localStorage.getItem("durationSelected");
      let durationTime = Cookies.get("durationSelected");
      var _this = this;
      // 从父窗口向iframe窗口发送数据
      document
        .getElementById("myiframe")
        .contentWindow.postMessage({ cmd: "chatstart" }, "*");
      _this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        // content: "收到HA的消息",
        content: "收到"+type+"消息",
      });
      // 可以进行识别时发出提示音
      _this.appAnswerMusic.play();
      _this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        content:
          "[" +
          // localStorage.getItem("audioSelectedValue") +
          Cookies.get("audioSelectedValue") +
          "]实时语音转文字:开始",
      });
      // if (_this.endTime){
      //   clearTimeout(_this.endTime);
      //   if (document.getElementById("myiframe"))
      //     document
      //       .getElementById("myiframe")
      //       .contentWindow.postMessage({ cmd: "chatend" }, "*");
      // } 
      _this.endTime = setTimeout(() => {
        // 不说话10秒结束
        console.log(durationTime+"秒未结束");
        // 语音识别结束播放提示音
        _this.appAnswerEndMusic.play();
        _this.$store.commit("setChatLog", {
          time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
          content: durationTime+"秒无人声，实时识别结束",
        });
        clearTimeout(_this.chatend);
        if (document.getElementById("myiframe"))
          document
            .getElementById("myiframe")
            .contentWindow.postMessage({ cmd: "chatend" }, "*");
      }, durationTime * 1000);
      // 语音识别超过15秒自动停止
      _this.chatend = setTimeout(() => {
        // 语音识别结束播放提示音
        _this.appAnswerEndMusic.play();
        document.getElementById("myiframe")
              .contentWindow.postMessage({ cmd: "chatend" }, "*");
        if(_this.chat_context_item.trim().length() > 0){
          _this.commit();
        }
        if (document.getElementById("myiframe"))
          document
            .getElementById("myiframe")
            .contentWindow.postMessage({ cmd: "chatend" }, "*");
      }, 15 * 1000);
      window.onmessage = function (e) {
        switch (e.data.cmd) {
          case "chatchange":
            console.log('change---')
            clearTimeout(_this.endTime);
            _this.chat_context_item = e.data.params.currentText;
            document.getElementById("chat_context_item").value =
              e.data.params.currentText;
            break;
          case "aWorldend": // 识别变化时，走不到一句话结束
            clearTimeout(_this.endTime);
            clearTimeout(_this.chatend);
            console.log('end----')
            _this.chat_context_item = e.data.params.currentText;
            document.getElementById("chat_context_item").value =
              e.data.params.currentText;
            document
              .getElementById("myiframe")
              .contentWindow.postMessage({ cmd: "chatend" }, "*");
            _this.commit();
            // 语音识别结束播放提示音
            _this.appAnswerEndMusic.play();
            _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content:
                "[" +
                // localStorage.getItem("audioSelectedValue") 
                Cookies.get("audioSelectedValue")
                +
                "]实时语音转文字:结束" +
                e.data.params.currentText,
            });
            break;

          case "chatError": //识别出错
            _this.$store.commit("setChatLog", {
                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                content:
                  "实时语音转文字:" +
                  e.data.params.currentText,
              });
              //clearTimeout(_this.endTime);
              clearTimeout(_this.chatend);
              // _this.appAnswerEndMusic.play();
              // document
              // .getElementById("myiframe")
              // .contentWindow.postMessage({ cmd: "chatend" }, "*");
              if(_this.chat_context_item.trim()){
                console.log('发送消息-----')
                _this.commit();
              }
              break;
        }
      };
    },
    handleKeyCode(e) {
      var button = document.getElementById("commit_button");
        if (e.keyCode == 13) {
          if (!(e.ctrlKey || e.metaKey)) {
            e.cancelBubble = true; //ie阻止冒泡行为
            e.stopPropagation(); //Firefox阻止冒泡行为
            e.preventDefault(); //取消事件的默认动作*换行
            // 当前没有播放接收到的消息
            if( button.style.pointerEvents !== 'none'){
              this.commit();
            }
          } else {
            this.chat_context_item = this.chat_context_item + "\n";
          }
        }
      // enter键
    },
    // 发送消息
    async commit() {
      console.log('this.chat_context_item',this.chat_context_item)
      // if(!this.chat_context_item.trim()){
      if (this.chat_context_item.length == 0 || !this.chat_context_item.trim()) {
        this.$message.info("请输入消息");
        return;
      }
      var param = {
        model_type: 1,
        role_type: 1,
        user_id: this.currentUserId,
        sender_type: 2,
        sender_id: this.loginUserInfo.userId,
        sender_name: this.userInfoDetails.account.name,
        chat_message: this.chat_context_item,
        volume:this.volume,
        remark:this.remark
      };
      if(param.chat_message.length == 0 || !param.chat_message.trim()) return false;
      console.log('发送消息',param)
      await chatMessage(param)
        .then((res) => {
          console.log("调用接口的结果", res);
          if (res.code == 0 && this.chat_context_item.trim !== "") {
            console.log("发送成功", res);
            this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "消息发送成功："+ param.chat_message,
            });
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: this.chat_context_item,
              flag: "success",
              modeltype:1,
              id:Date.parse(new Date())
            });
          } else {
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: this.chat_context_item,
              flag: "fail",
              modeltype:1,
              id:Date.parse(new Date())
            });

            this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "消息发送失败："+ res.code+"-"+res.message +"    当前token:"+window.localStorage["token"] +",当前token过期时间："+window.localStorage["expiration"],
            });
          }
          this.chat_context_item = "";
          document.getElementById("chat_context_item").value = "";
          this.updated();
        })
        .catch((error) => {
          console.log("获取失败", error);
          this.$store.commit("setChatArray", {
            roletype: 1,
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            name: "我",
            message: this.chat_context_item,
            flag: "fail",
            modeltype:1,
            id:Date.parse(new Date())
          });

          this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "消息发送失败"+ error +"    当前token:"+window.localStorage["token"] +",当前token过期时间："+window.localStorage["expiration"],
          });
          this.chat_context_item = "";
          this.updated();
        });
    },
    logmode() {
      this.showlog = !this.showlog;
      this.$emit('transmit', this.showlog)
      console.log('对话组件变化,this.showlog-------------',this.showlog)
      // this.speak({text:'你好'});
    },
    // 获取聊天记录
    async getChatRecords() {
      var param = {
        isUserID: 1,
        userID: this.currentUserId,
        isDate: 1,
        date: new Date(new Date().getTime() - 1 * 60 * 60 * 1000).Format(
          "yyyy-MM-dd hh:mm:ss"
        ), //1小时前
        date2: new Date().Format("yyyy-MM-dd hh:mm:ss"),
      };
      // 聊天记录查询
      await chatRecoeds(param)
        .then((res) => {
          if (res.code == 0) {
            let data = res.data.records;
            // 清空聊天记录
            this.$store.commit("setChatArrayNull");
            var arr=[]
            data.forEach((item,index) => {
              if(item.model_type == 2){
                var audio=new Audio()
                audio.src=item.chat_message
                var duration=audio.duration

                if (isNaN(duration)) {
                  audio.currentTime = 1e101;
                  audio.ontimeupdate = () => {
                    audio.ontimeupdate = () => { return; };
                    // 不重新设置currtTime,会直接触发audio的ended事件，因为之前将currentTime设置成了一个比音频时长还大的值。所以要将currentTime重置为初始状态。
                    // 注: 这里有一个问题，直接设置为0 是不起作用的。需要重新设置一下audio.currentTime = 1e101;然后再设置为
                    audio.currentTime = 1e101;
                    audio.currentTime = 0;
                    duration=Math.ceil(audio.duration)
                    arr[index]={
                      roletype: item.role_type,
                      time: item.update_time.replace("T", " "),
                      name: item.sender_name,
                      message: item.chat_message,
                      flag: "success",
                      modeltype:item.model_type,
                      duration: duration,
                      status:'stop',
                    }
                    // this.$store.commit("setChatArray", data0);
                  }
                }
              }else{
                arr[index]={
                  roletype: item.role_type,
                  time: item.update_time.replace("T", " "),
                  name: item.sender_name,
                  message: item.chat_message,
                  flag: "success",
                  modeltype:item.model_type,
                  status:'stop',
                }
                // this.$store.commit("setChatArray", {
                //   roletype: item.role_type,
                //   time: item.update_time.replace("T", " "),
                //   name: item.sender_name,
                //   message: item.chat_message,
                //   flag: "success",
                //   modeltype:item.model_type
                // });
              }
              // 设置聊天记录
            });
            setTimeout(()=>{
              arr.forEach(item=>{
                console.log('item',item)
                this.$store.commit("setChatArray", item);
              })
              this.updated();
            },100)

          } else {
            console.log("调用接口失败");
          }
        })
        .catch((error) => {
          console.log("获取失败", error);
        });
    },
      // 初始化文字转语音
    initSpeack(){
      if (!window.SpeechSynthesisUtterance) {
          console.log('当前浏览器不支持文字转语音服务')
          return;
      }
      this.speechUtterance = new SpeechSynthesisUtterance();
      console.log('初始化speechUtterance-----------',this.speechUtterance)
    },
    // 语音合成
    speak0( {text, speechRate, lang, volume, pitch} ) {
      let that = this;
      console.log('---------------------进行语音合成--------------------',text)
      // if (!text) {
      //     return;
      // }  
      var speechUtterance = new SpeechSynthesisUtterance();
      speechUtterance.rate = speechRate || 1;  //语速
      speechUtterance.lang = lang || 'zh-CN';  //语言
      speechUtterance.volume = volume ||0.5;   //声音volume 为0.0——1.0
      speechUtterance.pitch = pitch || 1;      //音调
      speechUtterance.text = text;

      console.log('speechUtterance',speechUtterance)
      var voices = window.speechSynthesis.getVoices()
      // 设置实例的voice，说话的声音
      speechUtterance.voice = voices.filter(function(voice) { return voice.localService == true && voice.lang == "zh-CN"; })[0];

      // 语音合成出错
      speechUtterance.addEventListener('error', (event) => {
          // 朗读错误时触发
          console.error('朗读错误:', event, event.error);
      });
      // 实例属性，语音合成结束
      speechUtterance.onend = function() {

          document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
          // endEvent && endEvent();
          console.log('朗读结束,准备进行语音识别');
          if (document.getElementById("myiframe")) {
              that.opentimeIdenty('mq');
          }
      };
      
      // 实例属性，语音合成开始
      speechUtterance.onstart = function() {
          // startEvent && startEvent();
          console.log('朗读开始');
      };
      speechUtterance.onerror= function() {
          // startEvent && startEvent();
          console.log('朗读错误');
      };
      //在语音合成过程中达到特定边界时触发的事件处理程序。
      speechUtterance.onboundary= () => {
          // console.log('边界');
      }
      speechSynthesis.speak(speechUtterance);
      return speechUtterance;
    },
    // 点击语音气泡
    controlAudio(data){
      var flat=''
      if(data.status == 'stop'){
        flat='play'
      }else{
        flat='stop'
      }
      console.log('flat',flat)

      console.log('this.chatArray-----',this.chatArray)
      this.chatArray.forEach(item=>{
        if(item.modeltype == 2 && item !== data)
        item.status='stop'
      })
      console.log('data',data)
      if(flat == 'play'){
        data.status='play'
        this.playAudio(data,false)
      }else{
        this.stopAudio(data)
      }
    },
    // 开始语音播放
    playAudio(data,flat){
      var _this=this
      data.status='play'
      // 当前百度文字转语音播放暂停
      if(localStorage.getItem("ttsSelectedValue") !== "jstts" && this.messageVoice !== null){
        _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "--取消正在播放的百度语音--",
        });
        this.messageVoice.pause()
        this.messageVoice.removeAttribute('src')
        this.messageVoice.load()
        this.messageVoice= null
      }
      // // 当前语音播放暂停
      if(this.currentAudio !== null){
        _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "--取消正在播放的语音消息--",
        });
        document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
        this.currentAudio.pause()
        this.currentAudio.removeAttribute('src')
        this.currentAudio.load()
        this.currentAudio= null
      }
      // // 取消正在播放的js合成语音
      if(localStorage.getItem("ttsSelectedValue") == "jstts"  && window.speechSynthesis.speaking){
        _this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "--取消正在播放的js消息--",
        });
        console.log('window.speechSynthesis.speaking',window.speechSynthesis.speaking,'取消正在播放的js')
        window.speechSynthesis.cancel()
      }
      // 当前语音播放
      this.currentAudio= null
      this.currentAudio=new Audio()
      this.currentAudio.src=data.message
      this.currentAudio.play()
      // 监听语音播放结束状态
      
        this.currentAudio.addEventListener('ended', function () {
            console.log('语音消息播放结束');

            document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
            _this.stopAudio(data)
            _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "语音消息播放结束",
            });
            if(flat){
              _this.$store.commit("setChatLog", {
                time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
                content: "trtc---开始语音识别",
              });
              if (document.getElementById("myiframe")) {
                _this.opentimeIdenty('mq');
              }
            }
        }, false);
        this.currentAudio.addEventListener('play', function () {
            console.log('语音消息播放开始');
            _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "语音消息播放开始",
            });
        }, false);
        this.currentAudio.addEventListener('error', function () {
            console.log('语音消息播放错误');

            document.getElementById('commit_button').setAttribute('style', 'background-color: #3280be;');
            _this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "语音消息播放错误---"+JSON.stringify(_this.currentAudio.error)+"  code----"+_this.currentAudio.error.code,
            });
        }, false);
    },
    // 停止语音播放
    stopAudio(data){
      console.log('------------stop 暂停语音播放---------',data)
      this.$store.commit("setChatLog", {
        time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
        content: "语音消息暂停播放---",
      });
      data.status='stop'
      this.currentAudio.pause()
      this.currentAudio = null
    },
    autoAudioLength(duration){
      var minLen = 5; // 设定最小长度
      var bubblesLen
      var maxLen = this.showchat ? 110 : 220; // 设定最大长度
      var firstLadder = 8; // 第一阶梯(3-10s)倍数
      var LastLadder = (maxLen - (minLen + 8 * firstLadder)) / 5; // 最后阶梯倍数
      if (duration <= 2) {
          bubblesLen = minLen;
      } else if (duration > 2 && duration <=10) {
          bubblesLen = minLen + (duration - 2) * firstLadder
      } else if (duration >=11 && duration <= 60) {
          if (duration % 10 === 0) { // 如果整除10
              bubblesLen = minLen + 65 + (duration-10) / 10 * LastLadder
          } else {
              bubblesLen = minLen + 65 + (duration - duration % 10 - 10) / 10 * LastLadder
          }
      } else {
          bubblesLen = maxLen;
      }
      bubblesLen = bubblesLen > maxLen ? maxLen : bubblesLen;
      return (bubblesLen / 20) + 'rem';
    },
    // 唤醒语音对话
    async awaken(){
      // 自动发送消息“你好”
      var param = {
        model_type: 1,
        role_type: 1,
        user_id: this.currentUserId,
        sender_type: 2,
        sender_id: this.loginUserInfo.userId,
        sender_name: this.userInfoDetails.account.name,
        chat_message: '你好',
        volume:50,
        remark:''
      };
      if(param.chat_message.length == 0) return false;
      console.log('发送消息',param)
      await chatMessage(param)
        .then((res) => {
          console.log("调用接口的结果", res);
          if (res.code == 0) {
            console.log("发送成功", res);

            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: '你好',
              flag: "success",
              modeltype:1,
              id:Date.parse(new Date())
            });
          } else {
            this.$store.commit("setChatArray", {
              roletype: 1,
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              name: "我",
              message: '你好',
              flag: "fail",
              modeltype:1,
              id:Date.parse(new Date())
            });

            this.$store.commit("setChatLog", {
              time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
              content: "消息发送失败："+ res.code+"-"+res.message +"    当前token:"+window.localStorage["token"] +",当前token过期时间："+window.localStorage["expiration"],
            });
          }
          this.chat_context_item = ""
          document.getElementById("chat_context_item").value = "";
          this.updated();
        })
        .catch((error) => {
          console.log("获取失败", error);
          this.$store.commit("setChatArray", {
            roletype: 1,
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            name: "我",
            message: '你好',
            flag: "fail",
            modeltype:1,
            id:Date.parse(new Date())
          });

          this.$store.commit("setChatLog", {
            time: new Date().Format("yyyy-MM-dd hh:mm:ss"),
            content: "消息发送失败"+ error +"    当前token:"+window.localStorage["token"] +",当前token过期时间："+window.localStorage["expiration"],
          });
          this.chat_context_item = "";
          this.updated();
        });
    },
  },


};
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}
ul li {
  list-style: none;
}
#box {
  position:relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
/* 文字唤醒按钮 */
.awakenIcon{
  position:fixed;
  /* margin-left: .5rem; */
  right:0.5rem;
  bottom:0.3rem;
  cursor: pointer;
}
.awakenIcon img {
  width: 5rem;
  height: 5rem;
  cursor: pointer;
}
::-webkit-input-placeholder {
  color: #fff;
}
:-moz-placeholder {
  color: #fff;
}
::-moz-placeholder {
  color: #fff;
}
::-ms-input-placeholder {
  color: #fff;
}
#onlineChat {
  text-align: left;
  display: flex;
  justify-content: center;
  margin-right: 5px;
}
.topIcon,
.topIcon img {
  width: 4rem;
  height: 4rem;
  margin-right: 0.5rem;
  position: absolute;
  right: 0;
  top: 1rem;
  cursor: pointer;
  z-index: 1;
}
.topIcon{
  margin-right: 0rem;
}
/* 滚动轴样式 */
/*  // 滚动轴整体，主要设置宽度*/
::-webkit-scrollbar {
  width: 6px;
  height: 2px;
}
/*// 滚动轴的背景区域*/
::-webkit-scrollbar-track {
  background: transparent;
}
/*// 滚动轴*/
::-webkit-scrollbar-thumb {
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  background: rgba(0, 0, 0, 0.1);
}

/*// 滚动轴浮动样式*/
::-webkit-scrollbar-thumb:hover {
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
  background: rgba(189, 118, 118, 0.3);
}
.chat_commento {
  width: 50rem;
  border-radius: 10px;
  border: 2px solid #f4f5f7;
  background: #fff;
  margin-top: 0;
  height: 40rem;
  box-sizing: border-box;
}
.clearfix::after {
  content: "";
  display: block;
  clear: both;
  width: 0;
  height: 0;
  line-height: 0;
  visibility: hidden;
}
/* top */
.chat_top {
  width: 100%;
  height: 2.6rem;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  padding-left: 1rem;
  padding-right: 1rem;
  font-size: 1.1rem;
  line-height: 2.6rem;
  box-sizing: border-box;
  font-weight: 550;
  border-width: 0px;
  /* position: sticky;
    top: 0; */
  background: #fff;
  border-bottom: 5px;
  border-color: #f4f5f7;
  border-style: solid;
}
/* middle */
/* 左边 */
.chat_middle {
  width: 100%;
  height: calc(100% - 9.4rem);
  position: relative;
  box-sizing: border-box;
  overflow-y: scroll;
  border-width: 0px;
}
.chat_left {
  width: 100%;
  margin-top: 1rem;
  margin-bottom: 1rem;
}
.chat_left_item_1 {
  color: #333;
  font-size: 0.7rem;
  width: 2.6rem;
  /* height: 90px; */
  float: left;
  margin-top: 0.5rem;
  margin-left: 0.5rem;
  margin-right: 0.5rem;
  text-align: center;
  word-wrap: break-word;
  word-break: break-all;
}
.chat_left_item_2 {
  width: 55%;
  /* min-height: 90px; */
  float: left;
  margin-top: 10px;
}
.chat_left_item_2 .chat_left_chat {
  float: left;
}
.chat_left_item_2 .chat_left_content {
  padding: 15px;
  margin-top: 10px;
  background-color: #f4f5f7;
  display: inline-block;
  border-radius: 10px;
  border-top-left-radius: 0px;
  max-width: 90%;
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-line;
  /* line-height: 1rem; */
}
.block{
  display:inline-block;
  width:10px;
}
/* 右边 */
.chat_right {
  width: 100%;
  margin-top: 1rem;
  margin-bottom: 1rem;
}
.chat_right_item_1 {
  width: 2.6rem;
  float: right;
  margin-top: 0.5rem;
  margin-left: 0.5rem;
  margin-right: 0.5rem;
  text-align: center;
  color: #333;
  font-size: 0.7rem;
}
.chat_right_item_2 {
  width: 55%;
  /* min-height: 90px; */
  float: right;
  margin-top: 10px;
}
#userimg {
  height: 2.6rem;
  max-width: 2.6rem;
}
.chat_right_time {
  width: 100%;
  text-align: right;
}
.clearfix::after {
  display: block;
  content: "";
  height: 0;
  clear: both;
}
.chat_right_content {
  max-width: 90%;
  word-wrap: break-word;
  word-break: break-all;
  float: right;
  padding: 15px;
  border-radius: 10px;
  margin-top: 10px;
  border-top-right-radius: 0px;
  background-color: rgb(149, 236, 105);
  color: #333;
  white-space: pre-line;
  position: relative;
}
/* foot */
.chat_foot {
  width: 100%;
  height: 6.5rem;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  position: relative;
}
.chat_context {
  width: 100%;
  height: 61%;
  box-sizing: border-box;
  outline: none;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  font-weight: 400;
  border-width: 0px;
  /* padding: 16px;
  font-size: 16px;
  line-height: 24px; */
  padding: 0.9rem;
  font-size: 0.9rem;
  line-height: 1rem;
}
#commit_button {
  /* width: 80px;
  height: 30px; */
  width: 4rem;
  height: 1.55rem;
  color: white;
  background-color: rgb(50, 128, 190);
  /* line-height: 30px; */
  line-height: 1.55rem;
  text-align: center;
  border-radius: 5px;
  position: absolute;
  right: 0.5rem;
  bottom: 1rem;
  margin-right: 0.5rem;
  cursor: pointer;
}
.chat_context {
  /* 文本框不能缩放 */
  resize: none;
  overflow-y: scroll;
}
.chat_context::placeholder {
  color: black;
  font-weight: 500k;
}
.line {
  width: 100%;
  border-top: 1px;
  border-color: #f4f5f7;
  border-style: solid;
}
.warn {
  vertical-align: middle;
  float: right;
  /* margin: 23.5px 10px 23.5px 0; */
  width: 25px;
  cursor: pointer;
  position: absolute;
  left: -30px;
  top: 50%;
  transform: translateY(-50%);
}
.audio{
  /* vertical-align: middle;
  float: left; */
  width: 1.2rem;
  cursor: pointer;
  /* position: absolute; */
  /* left: -30px;
  top: 50%;
  transform: translateY(-50%); */
}
.logList {
  height: 40rem;
  width: 13rem;
  background: #fff;
  border: 2px solid #f4f5f7;
  overflow-x: hidden;
  box-sizing: border-box;
  overflow-y: scroll;
  border-radius: 10px;
}
.logContent {
  padding: 0 1rem 0 1rem;
  font-size: 0.7rem;
}
.chat_log {
  /* width: 80px;
  height: 30px; */
  width: 4rem;
  height: 1.55rem;
  color: white;
  background-color: rgb(50, 128, 190);
  /* line-height: 30px; */
  line-height:1.55rem;
  text-align: center;
  border-radius: 5px;
  position: absolute;
  right: 5.5rem;
  bottom: 1rem;
  margin-right: 0.5rem;
  cursor: pointer;
}
.logTime {
  line-height: 1.2rem;
}
.logMessage {
  line-height: 1.5rem;
}
</style>

